package com.kyb.impl;

import com.kyb.dao.IDepartmentDao;
import com.kyb.entity.Department;
import com.kyb.entity.User;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

import com.kyb.util.BaseDB;


public class DepartmentDaoImpl extends BaseDB implements IDepartmentDao {

	Connection conn = null;
	PreparedStatement pstmt = null;
	ResultSet rs = null;
	
	public boolean addDepartment(Department department) {
		try {
			conn = getConn();
			String sql = "insert into department(department_id,department_name,parent_id) values"+"(?,?,?)";
			pstmt = conn.prepareStatement(sql);
			pstmt.setLong(1, department.getId());
			pstmt.setString(2, department.getName());
			pstmt.setString(3, department.getParentId());
		
			int flag = pstmt.executeUpdate();

			if (flag > 0) {
				return true;
			}

		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			closeAll(conn, pstmt, rs);
		}
		
		return false;
}

	@Override
	public boolean updateDepartment(Department department) {
		try {
			conn = getConn();
			String sql = "update department set department_name=?,parent_id=? where department_id=?";

			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1, department.getName());
			pstmt.setString(2, department.getParentId());
			pstmt.setInt(3, department.getId());
			int flag = pstmt.executeUpdate();

			if (flag > 0) {
				return true;
			}

		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			closeAll(conn, pstmt, rs);
		}
		return false;
	}

	@Override
	public boolean deleteDepartment(String deptId) {
		try {
			conn = getConn();
			String sql ="delete from department where department_id = ?";
			pstmt = conn.prepareStatement(sql);
			pstmt.setInt(1,Integer.parseInt(deptId));
			int flag = pstmt.executeUpdate();
			
			if (flag > 0) {
				return true;
			}

		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			closeAll(conn, pstmt, rs);
		}
		return false;
	}

	@Override
	public List<Department> getAllDept() {
		List<Department> list = new ArrayList<Department>();
		try {
			conn = getConn();
			String sql = "select department_id,department_name,parent_id from department";
			pstmt = conn.prepareStatement(sql);
			rs = pstmt.executeQuery();
			while (rs.next()) {
				Department dept = new Department();
				dept.setId(rs.getInt(1));
				dept.setName(rs.getString(2));
				dept.setParentId(rs.getString(3));
				list.add(dept);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return list;
	}
}
